package own.stu.bytebuffer.sim.agent;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.utility.JavaModule;

import static net.bytebuddy.matcher.ElementMatchers.not;


//@Slf4j
public class AgentTransform implements AgentBuilder.Transformer {

    private static String mapping_preffix = "org.springframework.web.bind.annotation";
    private static String mapping_suffix = "Mapping";

    public DynamicType.Builder<?> transform(
            DynamicType.Builder<?> builder,
            TypeDescription typeDescription,
            ClassLoader classLoader,
            JavaModule module) {

        // TODO del
        // log.info("actual name : {}", typeDescription.getActualName());
        System.out.println("actual name : " + typeDescription.getActualName());
        DynamicType.Builder.MethodDefinition.ReceiverTypeDefinition<?> interept = builder
                .method(
                        not(ElementMatchers.<MethodDescription>isStatic())
                                .and(ElementMatchers.<MethodDescription>isAnnotatedWith(
                                        ElementMatchers.<TypeDescription>nameStartsWith(mapping_preffix)
                                                .and(ElementMatchers.<TypeDescription>nameEndsWith(mapping_suffix))
                                )))
                .intercept(MethodDelegation.to(new SpringmvcInterceptor()));
        return interept;
    }
}
